<template>
	<view>
		<nav-header title="友商圈" custom-nav>
			<template v-slot:right>
				<view class="moments-top" @click="goToPublish">
					<svg-icon icon="camera-1" :width="50"></svg-icon>
				</view>
			</template>
		</nav-header>
		<view class="moments-bac">
			<view class="qun-bg">
				<image class="qun-bg" draggable="" :src="bgPicture" mode="scaleToFill" @click="topviewImage(bgPicture)"
					@longpress="selectImage">
				</image>
				<view class="background-image" @click.stop="selectImage"><svg-icon icon="camera-1" :width="50"></svg-icon>
				</view>
			</view>
			<view class="user-info" @click="goToMoments()">
				<text class="uname">{{ userInfo.nickName }}</text>
				<head-image class="img" :name="userInfo.nickName" :url="userInfo.headImageThumb"
					:size="100"></head-image>
			</view>
		</view>
		<!-- <view class="right-align"> {{ signature }}</view> -->
		<view class="moments-content">
			<view v-if="mList.length>0">
				<view class="content" v-for="(item, index) in mList" :key="item.id">
					<view class="user-info">
						<view class="content-img">
							<head-image class="img" :name="item.nickName" :url="item.headImageThumb"
								:size="65"></head-image>
						</view>
						<view style="margin-left: 15rpx;">
							<badge type="friend-group"></badge>
						</view>
						<text class="uname">{{ item.nickName }}</text>
					</view>
					<view class="publish">
						<view class="publish-text">
							{{ item.content }}
						</view>
						<view class="publish-img">
							<view v-for="(it, index) in item.picture" :key="index">
								<image :src="it" alt="" class="pimg" @click="previewImage(index, item)" />
							</view>
						</view>
						<view class="publish-loc text-xs-Regular" v-if="item.address">
							<svg-icon icon="定位" :width="28"></svg-icon>
							<text>{{ item.address }}</text>
						</view>
						<view class="publish-gn">
							<text class="gn-time">{{ item.createTime }}发布</text>
							<view class="gn-right remove-mask">
								<view v-show="selectedUserId === item.id">
									<view class="good-list">
										<view class="good" @click="toggleLike(index, item.id)">
											<uni-icons type="heart" size="18" style="padding-left: 10rpx;"></uni-icons>
											<text> {{ item.isLiked ? '已赞' : '点赞' }}
											</text>
										</view>
										<text>|</text>
										<view class="good" @click="toggleComment(index, item.id)">
											<uni-icons type="chatbubble" size="18"></uni-icons> <text>评论</text>
										</view>
									</view>
								</view>
								<!-- <uni-icons type="more-filled" size="28" @click="toggleActions(item.id)"></uni-icons> -->
								<view class="more-bac" @click="toggleActions(item.id)">
									<svg-icon icon="more" :width="48"></svg-icon>
								</view>
							</view>
						</view>
						<view class="publish-dz" v-if="item.starList.length > 0">
							<!-- <uni-icons type="heart" size="18" color="#118dd0"></uni-icons> -->
							<svg-icon icon="like-1" :width="32"></svg-icon>
							<view class="dz">
								<view>
									{{ item.starList.nameStr }}
								</view>
							</view>
						</view>
						<view class="publish-dz" v-if="item.isLiked && (item.starList.length === 0)">
							<uni-icons type="heart" size="18" color="#118dd0"></uni-icons>
						</view>

						<!-- 评论框 -->
						<view class="remove-mask" v-if="commentId === item.id"
							style="display: flex; align-items: center;border:2px solid #ccc;">
							<input class="uni-input" v-model="content" placeholder="请输入评论"
								style="flex:1;border:none;" /></input>
							<button class="mini-btn" type="default" size="mini" style="border:none;"
								@click="submitComment(item.id, index)">评论</button>
						</view>

						<view class="publish-pl remove-mask" v-if="item.commentList.length > 0">
							<!-- 	<view style="padding-top: 10rpx;">
							<uni-icons type="chatbubble" size="20" color="#118dd0"></uni-icons>
						</view> -->
							<view class="pl remove-mask">
								<view v-for="(comment, commentIndex) in item.commentList" :key="commentIndex"
									style="padding-top: 10rpx;">


									<view @longpress="deleteComment(index, comment, commentIndex)">
										<view @click="replyComment(item, commentIndex)">
											<text>{{ comment.fromNickName }}</text>
											<text class="pl-text" v-if="Boolean(comment.atId)">回复</text>
											<text>{{ comment.atNickName }}</text> :
											<text class="pl-text">{{ comment.comment }}</text>
										</view>
									</view>

									<!-- 回复评论 -->
									<view class="remove-mask"
										v-if="replyingToCommentId === commentIndex && item.id === activeMomentUniqueId"
										style="display: flex; align-items: center;border:2px solid #ccc;">
										<input class="uni-input" v-model="content" placeholder="请输入评论"
											style="flex:1;border:none;color: #000;" />
										<button class="mini-btn" type="default" size="mini" style="border:none;"
											@click="submitComment(item.id, index, comment)">评论</button>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view v-else style="margin-top: 80px;">
				<view v-if="loading">
					<up-loading-icon text="努力加载中~"></up-loading-icon>
				</view>
				<view style="width: 70%;margin-left: 15vw;" v-else>
					<up-divider text="分割线" :dot="true"></up-divider>
				</view>
			</view>

		</view>
		<view class="mask" @click="close" v-if="showMask" />
	</view>
</template>

<script>
	import UNI_APP from '@/.env.js'
	// import DateUtils from '../utils/DateUtils.js'
	export default {
		data() {
			return {
				isFromImagePreview: false, // 添加标记，判断是否从图片预览返回
				isShow: false,
				mList: [],
				content: '',
				showMask: false,
				isLiked: false,
				selectedUserId: null,
				likdedId: false,
				showLoading: false,
				commentId: null,
				signature: '',
				bgPicture: 'https://axure-file.lanhuapp.com/md5__5101406288fb224480674487be13a2bd.jpg',
				List: [],
				params: {
					current: 1, // 第一页
					size: 10, // 每页十个},
				},
				loading: false, // 用于控制加载状态
				hasMoreData: true, // 用于判断是否还有更多数据
				userId: '',
				replyingToCommentId: null, // 正在回复的评论对象
				activeMomentUniqueId: null, // 添加一个变量来记录当前正在操作的朋友圈的唯一标识
			}
		},
		methods: {
			/**
			 * 上传朋友圈背景图
			 */
			selectAndUpload() {
				uni.chooseImage({
					count: 1,
					sourceType: ["album", "camera"], //album 从相册选图，camera 使用相机，默认二者都有。如需直接开相机或直接选相册，请只使用一个选项
					sizeType: ['original'], //original 原图，compressed 压缩图，默认二者都有
					success: (res) => {
						uni.uploadFile({
							url: UNI_APP.BASE_URL + '/friendCircle/updateBg',
							header: {
								accessToken: uni.getStorageSync("loginInfo").accessToken
							},
							filePath: res.tempFiles[0].path, // 要上传文件资源的路径
							name: 'file',
							success: (res) => {
								this.getFriendCircleInfo()
							},
							fail: (err) => {
								console.error(err);
							}
						})
					}
				})
			},
			close() {
				console.log("关闭其他的选项")
				this.replyingToCommentId = null
				this.selectedUserId = null
				this.commentId = null
				this.showMask = false
			},
			// 图片预览功能
			topviewImage(url) {
				this.isFromImagePreview = true; // 标记即将进入图片预览
				let urls = [];
				urls.push(url);
				uni.previewImage({
					urls: urls,
					current: 0
				});
			},
			goToMoments() {
				uni.navigateTo({
					url: "/pageSubOne/moments/user-moments?type=" + 1
				})
			},
			// 回复评论功能
			replyComment(item, commentIndex) {
				// 开启遮罩
				this.showMask = true
				this.commentId = null
				this.selectedUserId = null
				this.activeMomentUniqueId = item.id
				if (this.replyingToCommentId === commentIndex) {
					this.replyingToCommentId = null;
				} else {
					this.replyingToCommentId = commentIndex;

				}

			},

			selectImage() {
				uni.chooseImage({
					count: 1, // 选择一张图片
					success: async (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						this.uploading = true;
						try {
							const uploadRes = await this.uploadImage(tempFilePaths[0]);
							uni.showToast({
								title: '更改背景成功',
								icon: 'success'
							});
							this.getFriendCircleInfo()
						} catch (error) {
							console.error('上传失败：', error);
						} finally {
							this.uploading = false;
						}
					}
				});
			},
			async uploadImage(filePath) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: UNI_APP.BASE_URL + '/friendCircle/updateBg',
						header: {
							accessToken: uni.getStorageSync("loginInfo").accessToken
						},
						filePath: filePath,
						name: 'file',
						success: (uploadFileRes) => {
							resolve(uploadFileRes.data);
						},
						fail: (error) => {
							reject(error);
						},
					});
				});
			},

			goToPublish() {
				uni.navigateTo({
					url: "/pageSubOne/moments/push-momnets?type=" + 1
				})
			},

			// 图片预览
			previewImage(index, item) {
				this.isFromImagePreview = true; // 标记即将进入图片预览
				uni.previewImage({
					urls: item.picture,
					current: index
				});
			},



			// 点赞
			toggleLike(index, id) {
				const item = this.mList[index];
				if (!item.isLiked) {
					let star = {
						fromNickName: this.userInfo.nickName,
						fromUserId: this.userId
					}
					item.starList.push(star)
					const nickNameArray = item.starList.map(star => star.fromNickName);
					const nameStr = nickNameArray.join(', ');
					item.starList.nameStr = nameStr
					const circleId = id
					this.$http({
						url: '/friendCircle/star',
						data: {
							circleId: circleId
						},
						method: 'POST'
					}).then(res => {});

				} else {
					const circleId = id
					this.$http({
						url: '/friendCircle/star',
						data: {
							circleId: circleId
						},
						method: 'POST'
					}).then(res => {});
					const newArray = item.starList.filter((star) => Number(star.fromUserId) !== Number(this.userId))
					item.starList = newArray
					const nickNameArray = item.starList.map(star => star.fromNickName);
					const nameStr = nickNameArray.join(', ');
					item.starList.nameStr = nameStr
				}

				item.isLiked = !item.isLiked;
				this.selectedUserId = null
				// 追加评论
			},

			//评论
			toggleComment(index, id) {
				this.selectedUserId = null
				this.showMask = true
				this.replyingToCommentId = null
				if (this.commentId === id) {
					this.commentId = null;
				} else {
					this.commentId = id;
				}
			},


			// todo 评论方法
			submitComment(id, index, info) {

				const content = this.content
				if (content.trim().length === 0) {
					this.commentId = null;
					console.log('没有提交任何评论')
					return
				}
				const item = this.mList[index];
				const nickename = this.userInfo.nickName
				const userId = this.userId

				const circleId = id

				// 组装数据 方便前台展示
				let comment = {
					fromNickName: nickename,
					comment: content,
					fromUserId: userId
				}

				let atId = ''
				let userComment = ''
				if (info != null) {
					atId = info.fromUserId
					// 被回复的用户
					userComment = info.fromNickName
				}


				if (Boolean(atId) && Boolean(userComment)) {
					console.log('进来了')
					comment = {
						atId: atId,
						atNickName: userComment,
						fromNickName: nickename,
						comment: content,
						fromUserId: userId
					}
					console.log('回复他人评论!!')
					// value 不为 null、undefined、空字符串、数字 0、false 等假值时执行的代码
				}
				console.log('comment', comment)
				item.commentList.push(comment)

				let formData = {
					circleId: circleId,
					content: content,
					atId: atId
				}
				this.$http({
					url: '/friendCircle/comment/add',
					data: formData,
					method: 'POST'
				}).then(res => {
					this.content = null,
						this.commentId = null;
					this.replyingToCommentId = null;
				});
			},

			// 删除评论
			deleteComment(index, comment, commentIndex) {



				if (comment.fromUserId != this.userId) {
					console.log('不是该用户发的评论，无法删除')
					return
				}



				uni.showModal({
					title: '确认删除',
					content: '确定要删除这个评论吗？',
					success: (res) => {
						if (res.confirm) {

							// 前端评论移除
							const item = this.mList[index];
							const commentList = item.commentList
							const newCommentList = commentList.filter((_, i) => i !== commentIndex);
							item.commentList = newCommentList

							const id = comment.id
							this.$http({
								url: '/friendCircle/comment/delete?id=' + id,
								method: 'POST'
							}).then(res => {
								this.showLoading = false
							});
						}
					}
				});
			},


			showGood() {
				this.isShow = !this.isShow
			},
			toggleActions(userId) {
				this.showMask = true
				if (this.selectedUserId === userId) {
					this.selectedUserId = null;
				} else {
					this.selectedUserId = userId;
				}
			},
			getFriendCircleInfo() {
				this.showLoading = true
				this.$http({
					url: '/friendCircle/getInfo',
					method: 'GET'
				}).then(res => {
					this.bgPicture = res.bgPicture

					this.userId = res.userId
					this.signature = res.signature
					this.showLoading = false
				});
			},
			getData() {
				this.showLoading = true
				this.loading = true
				const that = this

				let pageNum = this.params.current;
				let pageSize = this.params.size;
				this.$http({
					url: `/friendCircle/BUSINESS/listHall?pageNum=${pageNum}&pageSize=${pageSize}`,
					method: 'GET'
				}).then(res => {
					const circleList = res.list
					console.log("res", res)
					if (circleList.length > 0) {
						let mLists = []
						for (const item of circleList) {
							if (!item.user) {
								continue
							}
							let isLiked = false

							// todo 后续处理点赞人
							if (item.starList.length > 0) {
								const nickNameArray = item.starList.map(star => star.fromNickName);
								const nameStr = nickNameArray.join(', ');
								item.starList.nameStr = nameStr
								for (const userStar of item.starList) {
									if (that.userId === userStar.fromUserId) {
										isLiked = true
									}
								}
							}
							let list = {
								id: item.id,
								isLiked: isLiked,
								nickName: item.user.nickName,
								content: item.content,
								picture: item.pictureList,
								// createTime: DateUtils.formatFriendlyTime(item.createTime),
								createTime: item.createTime,
								address: item.address,
								headImageThumb: item.user.headImageThumb,
								starList: item.starList,
								commentList: item.commentList
							}
							mLists.push(list);
						}
						console.log("this.mList", this.mList)
						this.mList = this.mList.concat(mLists); // 拼接新数据到现有数据列表
						this.loading = false
					} else {
						this.hasMoreData = false
						this.loading = false
					}
					this.showLoading = false
					uni.stopPullDownRefresh();
				});
			},


		},


		// 上拉加载
		onReachBottom() {
			this.showLoading = true
			if (!this.hasMoreData) {
				return
			}
			this.params.current++;
			this.getData()

		},

		// 下拉刷新
		onPullDownRefresh() {
			this.params.current = 1;
			this.hasMoreData = true
			this.mList = []
			this.getData()
		},



		onShow() {
			// 如果是从图片预览返回，不重新加载数据
			if (this.isFromImagePreview) {
				this.isFromImagePreview = false; // 重置标记
				return;
			}
			this.params.current = 1;
			this.hasMoreData = true
			this.mList = []
			this.getFriendCircleInfo()
			this.getData()
		},
		onLoad() {
			console.log('测试onLoad')
		},
		computed: {
			userInfo() {
				return this.userStore.userInfo;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.moments-top {
		width: 100%;
		background-color: $white;
		z-index: 100;
		display: flex;
		justify-content: flex-end;

		.top-img {
			padding: 20rpx 20rpx 10rpx 20rpx;
			width: 50rpx;
			height: 50rpx;
		}
	}

	.moments-bac {
		width: 100%;
		position: relative;

		.qun-bg {
			width: 100%;
			height: 200px;
		}

		.background-image {
			margin-top: -320rpx;
			margin-left: 20rpx;
			/* #ifdef APP-PLUS */
			z-index: 100;
			/* #endif */
		}


		.bac-img {
			width: 390px;
			background-color: #000;
		}

		.user-info {
			display: flex;
			align-items: center;
			justify-content: flex-end;
			position: absolute;
			padding: 40rpx;
			right: 0;
			bottom: -30px;

			.uname {
				text-align: right;
				width: 75%;
				margin-right: 20rpx;
				margin-bottom: 10rpx;
				color: #fff;
				font-size: 38rpx;
				white-space: nowrap;
				text-overflow: ellipsis;
				overflow: hidden;
			}
		}
	}

	.mask {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100vh;
		// background-color: rgba(0, 0, 0, 0.5);
		z-index: 2;
	}

	//在遮罩的上一层
	.remove-mask {
		position: relative;
		z-index: 3;
	}

	.right-align {
		margin-left: 200rpx;
		margin-top: 20rpx;
		text-align: right;
		/* 文字居右 */
		white-space: normal;
		/* 自动换行 */
		word-wrap: break-word;
		/* 处理长单词换行 */
	}

	.uni-input {
		/* 可以根据需要调整输入框的样式 */
		padding: 5px;
	}

	.mini-btn {
		/* 可以根据需要调整按钮的样式 */
		background-color: #007AFF;
		color: #fff;
		padding: 5px 10px;
		border-radius: 5px;
	}

	.moments-content {
		width: 100%;

		.content {
			padding: 50rpx 24rpx 0 24rpx;

			.user-info {
				display: flex;
				align-items: center;

				.content-img {
					width: 70rpx;
					height: 70rpx;
				}

				.uname {
					margin-left: 20rpx;
					white-space: nowrap;
					text-overflow: ellipsis;
					overflow: hidden;
					color: #118dd0;
				}
			}

			.publish {
				padding-left: 85rpx;

				.publish-text {
					font-size: 30rpx;
				}

				.publish-img {
					display: flex;
					flex-wrap: wrap;

					.pimg {
						width: 190rpx;
						height: 190rpx;
						padding: 10rpx 20rpx 0 0;
					}
				}

				.publish-loc {
					display: flex;
					align-items: center;
					gap: 8rpx;
					font-size: 25rpx;
					color: $brand-700;
					margin-top: 16rpx;
				}

				.publish-gn {
					display: flex;
					justify-content: space-between;
					align-items: center;

					.gn-time {
						font-size: 25rpx;
						color: #aaa;
					}

					.gn-right {
						display: flex;
						justify-content: flex-end;
						position: relative;
						flex: 1;
						z-index: 4;

						.more-bac {
							height: 48rpx;
							padding: 0 16rpx;
							border-radius: 24rpx;
							background-color: $gray-200;
						}
					}

					.good-list {
						position: absolute;
						right: 0;
						top: 60rpx;
						display: flex;
						align-items: center;
						gap: 24rpx;
						background-color: #d8d8d8;
						padding: 12rpx 16rpx;
						border-radius: 16rpx;
						// z-index: 100;

						/* 增加三角形箭头 */
						&::before {
							content: '';
							position: absolute;
							top: -20rpx;
							right: 20rpx;
							border: 10rpx solid transparent;
							border-bottom-color: #d8d8d8;
						}

						.good {
							display: flex;
							align-items: center;
							gap: 8rpx;
							// padding: 24rpx 32rpx;
							font-size: 25rpx;


							text {
								// padding: 10rpx;
							}
						}
					}
				}

				.publish-dz {
					display: flex;
					gap: 8rpx;
					border-bottom: 1px solid #eee;
					padding-bottom: 10rpx;

					.dz {
						display: flex;
						align-items: center;
						flex-wrap: wrap;
						font-size: 25rpx;
						color: $brand-500;
					}
				}

				.publish-pl {
					// display: flex;

					.pl {
						font-size: 25rpx;
						color: $brand-500;

						.pl-text {
							color: #000;
						}
					}
				}
			}
		}
	}
</style>